#include "mylog.h"
#include <stdio.h>
#define config_file_path "../config/log.ini"
// 自定义日志处理器函数  
 void my_log_handler(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) {  
   
   //从日志的配置文件中读取一些配置 glib里面对key-value的操作
   GKeyFile *keyFile = g_key_file_new();
   g_key_file_load_from_file(keyFile,config_file_path,G_KEY_FILE_NONE,NULL);

   gint level = g_key_file_get_integer(keyFile,"config","level",NULL);
   g_print("level%d\n",level);
   //log_level打印日志级别 debug 1 << 7
    if (log_level>level)
    {
        return;

    }

    gchar* logPath = g_key_file_get_string(keyFile,"config","path",NULL);
    g_print("path=%s\n",logPath);
    gchar* domain = g_key_file_get_string(keyFile,"config","domain",NULL);
    g_print("domain=%s\n",domain);
    gchar* method = g_key_file_get_string(keyFile,"config","method",NULL);
    g_key_file_free(keyFile);

    
    // 获取当前的日期和时间
    GDateTime *current_time = g_date_time_new_now_local();
    // 将时间格式化为字符串
    // 这里使用的格式为 "YYYY-mm-dd HH:MM:SS"
    char *time_str = g_date_time_format(current_time, "%Y-%m-%d %H:%M:%S");
    log_domain = (log_domain==NULL|| log_domain=="")? domain:log_domain;
    
    if(g_str_match_string("console",method,FALSE)){
        //输出到控制台
        fprintf(stdout, "%s %s: %s\n",time_str, log_domain, message);
    }
   
    if(g_str_match_string("file",method,FALSE)){
        // 打开日志文件，追加方式写入
        FILE *log_file = fopen(logPath, "a");
        if (log_file == NULL) {
            perror("fopen");
            return;
        }
        // 将日志信息写入到文件
        fprintf(log_file, "%s %s: %s\n",time_str, log_domain, message);
        // 关闭日志文件
        fclose(log_file);
    }
    
}